package com.nidu.demo.file.storage;

import com.nidu.demo.common.enums.FileStorageTypeEnum;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 文件存储工厂
 *
 * @author auto
 */
@Component
@RequiredArgsConstructor
public class FileStorageFactory {

    private final List<FileStorage> fileStorages;
    
    private Map<Integer, FileStorage> storageMap;

    /**
     * 获取文件存储实现
     *
     * @param storageType 存储类型
     * @return 文件存储实现
     */
    public FileStorage getFileStorage(Integer storageType) {
        if (storageMap == null) {
            storageMap = fileStorages.stream()
                    .collect(Collectors.toMap(FileStorage::getStorageType, Function.identity()));
        }
        
        FileStorage fileStorage = storageMap.get(storageType);
        if (fileStorage == null) {
            throw new IllegalArgumentException("不支持的存储类型：" + storageType);
        }
        
        return fileStorage;
    }

    /**
     * 获取文件存储实现
     *
     * @param storageType 存储类型枚举
     * @return 文件存储实现
     */
    public FileStorage getFileStorage(FileStorageTypeEnum storageType) {
        return getFileStorage(storageType.getType());
    }
}
